from flask import request, jsonify
from flask_jwt_extended import jwt_required
from sqlalchemy import or_, func

from app.core.extensions import db
from app.models import User, AdminLog
from app.models.agents import Agent
from . import admin_blueprint
from app.services.decorators import admin_required
import datetime
from .utils import get_admin_id


@admin_blueprint.route('/users', methods=['GET'])
@admin_required
def get_users():
    """获取用户列表"""
    # 获取分页参数
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 20, type=int)
    search = request.args.get('search', '')
    user_id = request.args.get('user_id', '')
    # 构建查询 - 手动确保租户过滤
    from flask import g

    # 获取当前租户ID
    tenant_id = getattr(g, 'tenant_id', None)
    is_super_admin = getattr(g, 'is_super_admin', False)

    # 构建基础查询
    query = User.query

    # 如果不是超级管理员，添加租户过滤
    if not is_super_admin and tenant_id is not None:
        query = query.filter(User.tenant_id == tenant_id)

    # 如果有搜索关键词，按名称或手机号搜索
    if search:
        query = query.filter(
            or_(
                User.nick_name.like(f'%{search}%'),
                User.mobile.like(f'%{search}%'),
            )
        )

    if user_id:
        query = query.filter(User.user_id == user_id)

    # 计算总记录数 - 使用原生SQLAlchemy确保租户过滤
    count_query = db.session.query(func.count(User.user_id))

    # 手动添加租户过滤
    if not is_super_admin and tenant_id is not None:
        count_query = count_query.filter(User.tenant_id == tenant_id)

    # 添加搜索条件
    if search:
        count_query = count_query.filter(
            or_(
                User.nick_name.like(f'%{search}%'),
                User.mobile.like(f'%{search}%'),
            )
        )

    if user_id:
        count_query = count_query.filter(User.user_id == user_id)

    total = count_query.scalar() or 0
    
    # 计算总页数
    pages = (total + per_page - 1) // per_page if total > 0 else 1
    
    # 处理分页
    users = query.order_by(User.create_time.desc()).offset((page - 1) * per_page).limit(per_page).all()
    
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': {
            'total': total,
            'pages': pages,
            'page': page,
            'per_page': per_page,
            'items': [user_to_dict(user) for user in users]
        }
    })


@admin_blueprint.route('/users/search', methods=['GET'])
@jwt_required()
def search_users():
    """搜索用户
    用于在选择代理关联用户时快速搜索用户
    """
    keyword = request.args.get('keyword', '')
    limit = request.args.get('limit', 20, type=int)
    
    if not keyword:
        return jsonify({
            'code': 0,
            'message': '搜索成功',
            'data': []
        })
    
    # 按名称或手机号搜索
    query = User.query.filter(
        or_(
            User.nick_name.like(f'%{keyword}%'),
            User.mobile.like(f'%{keyword}%'),
            User.user_id.like(f'%{keyword}%')
        )
    )
    
    # 限制返回数量
    users = query.limit(limit).all()
    
    # 检查用户是否已经是代理
    user_data = []
    for user in users:
        user_dict = user_to_dict(user, simple=True)
        # 添加是否已是代理的标记
        is_agent = Agent.query.filter_by(user_id=user.user_id).first() is not None
        user_dict['is_agent'] = is_agent
        user_data.append(user_dict)
    
    return jsonify({
        'code': 0,
        'message': '搜索成功',
        'data': user_data
    })


@admin_blueprint.route('/users/<int:user_id>', methods=['GET'])
@jwt_required()
@admin_required
def get_user(user_id):
    """获取用户详情"""
    user = User.query.get_or_404(user_id)
    
    # 添加操作日志
    admin_id = get_admin_id()
    log = AdminLog(
        admin_id=admin_id,
        action='查看用户',
        ip=request.remote_addr,
        details=f'查看用户 {user.nick_name}'
    )
    db.session.add(log)
    db.session.commit()
    
    return jsonify({
        'code': 0,
        'message': '获取成功',
        'data': user_to_dict(user)
    })


@admin_blueprint.route('/users/add', methods=['POST'])
@jwt_required()
@admin_required
def add_user():
    """添加新用户"""
    data = request.json

    # 提取表单数据
    nick_name = data.get('nick_name', '新用户')
    mobile = data.get('mobile')
    mp_open_id = data.get('mp_open_id')
    points = data.get('points', 0)
    usage_count = data.get('usage_count', 0)

    # 创建新用户
    user = User(
        nick_name=nick_name,
        mobile=mobile,
        mp_open_id=mp_open_id,
        points=points,
        usage_count=usage_count,
        create_time=datetime.datetime.now()
    )

    db.session.add(user)

    # 添加操作日志
    admin_id = get_admin_id()
    log = AdminLog(
        admin_id=admin_id,
        action='添加用户',
        ip=request.remote_addr,
        details=f'添加用户 {nick_name}'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '添加成功',
        'data': user_to_dict(user)
    })


@admin_blueprint.route('/users/edit/<int:user_id>', methods=['POST'])
@admin_required
def edit_user(user_id):
    """编辑用户信息"""
    user = User.query.get_or_404(user_id)
    data = request.json

    # 更新用户信息
    if 'nick_name' in data:
        user.nick_name = data['nick_name']
    if 'mobile' in data:
        user.mobile = data['mobile']
    if 'points' in data:
        user.points = data['points']
    if 'usage_count' in data:
        user.usage_count = data['usage_count']
    if 'distribution_rate' in data:
        user.distribution_rate = data['distribution_rate']
    if 'role' in data:
        user.role = data['role']
    # 添加操作日志
    admin_id = get_admin_id()
    log = AdminLog(
        admin_id=admin_id,
        action='编辑用户',
        ip=request.remote_addr,
        details=f'编辑用户 {user.nick_name} (ID: {user.user_id})'
    )
    db.session.add(log)

    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '更新成功',
        'data': user_to_dict(user)
    })


@admin_blueprint.route('/users/delete/<int:user_id>', methods=['POST'])
@jwt_required()
@admin_required
def delete_user(user_id):
    """删除用户"""
    user = User.query.get_or_404(user_id)

    # 添加操作日志
    admin_id = get_admin_id()
    log = AdminLog(
        admin_id=admin_id,
        action='删除用户',
        ip=request.remote_addr,
        details=f'删除用户 {user.nick_name} (ID: {user.user_id})'
    )
    db.session.add(log)

    # 删除用户
    db.session.delete(user)
    db.session.commit()

    return jsonify({
        'code': 0,
        'message': '删除成功'
    })


def user_to_dict(user, simple=False):
    """将用户对象转为字典
    
    参数:
    - user: User对象
    - simple: 是否返回简化版信息(用于下拉选择列表)
    """
    if simple:
        return {
            'user_id': user.user_id,
            'nick_name': user.nick_name,
            'mobile': user.mobile,
            'avatar_url': user.avatar_url
        }
    
    return {
        'user_id': user.user_id,
        'nick_name': user.nick_name,
        'gender': user.gender,
        'avatar_url': user.avatar_url,
        'mobile': user.mobile,
        'usage_count': user.usage_count,
        'create_time': user.create_time.strftime('%Y-%m-%d %H:%M:%S') if user.create_time else None,
        'is_agent': hasattr(user, 'agent') and user.agent is not None,
        'role': user.role,
        'balance': float(user.balance) if user.balance else 0.00,
        'distribution_rate': float(user.distribution_rate) if user.distribution_rate else 0.0,
    }
